package no.saiboten.drumcalendar.user;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WinnerServiceImpl implements WinnerService {

	private final Logger LOGGER = Logger.getLogger(WinnerServiceImpl.class.getName());

	CalendarUserService userService;

	WinnerDao winnerDao;

	@Autowired
	public WinnerServiceImpl(CalendarUserService userService, WinnerDao winnerDao) {
		this.userService = userService;
		this.winnerDao = winnerDao;

	}

	@Override
	public Winners getWinners() {
		return winnerDao.getWinners();
	}

	@Override
	public void addWinner(Long day) {
		Winners winners = getWinners();
		Map<Long, String> winnerMap = winners.getWinners();
		if (winnerMap != null && winnerMap.get(day) == null) {

			String winner = findWinner(day);
			if (winner == null) {
				LOGGER.fine("No winner found. Maybe noone got the question right?");
				return;
			}

			winnerMap.put(day, winner);
			LOGGER.fine("Adding winner for day " + day + ": " + winner);
			winners.setWinners(winnerMap);
			winnerDao.saveWinners(winners);
		} else {
			LOGGER.fine("Winner already decided for day " + day);
		}

	}

	@Override
	public void addNewWinner(Long day) {
		Winners winners = getWinners();
		Map<Long, String> winnerMap = winners.getWinners();

		String winner = findWinner(day);
		if (winner == null) {
			LOGGER.fine("No winner found...");
			return;
		}
		winnerMap.put(day, winner);
		LOGGER.fine("Adding winner for day " + day + ": " + winner);
		winners.setWinners(winnerMap);
		winnerDao.saveWinners(winners);

	}

	protected String findWinner(Long day) {
		List<CalendarUser> users = userService.getAllUsers();
		List<CalendarUser> possibleWinners = new ArrayList<CalendarUser>();
		for (CalendarUser user : users) {
			Answer answer = user.getAnswers().get(day);
			if (answer != null && answer.isCorrectArtist() && answer.isCorrectSong()) {
				possibleWinners.add(user);
			}
		}

		Random random = new Random();
		if (possibleWinners.size() == 0) {
			LOGGER.fine("No winners found this day");
			return null;
		}
		int winner = random.nextInt(possibleWinners.size());
		CalendarUser winnerUser = possibleWinners.get(winner);
		if (winnerUser != null) {
			return winnerUser.getUserNameNotMail();
		}

		return null;
	}
}
